package com.system.controller;

import com.system.entity.Student;
import com.system.entity.Teacher;
import com.system.service.studentService;
import com.system.service.teacherService;
import com.system.util.CpachaUtil;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * 登陆页面
 */
@RequestMapping("/")
@Controller
public class SystemController {

    @Autowired
    private studentService studentService;
    @Autowired
    private teacherService teacherService;
    /**
     * 登陆页面
     * @param model
     * @return
     */
//    @RequestMapping(value = "/login",method = RequestMethod.GET)
//    public ModelAndView login(ModelAndView model){
//        model.setViewName("login");
//        return model;
//    }

    /**
     * 显示 验证码
     * @param request
     * @param vl
     * @param w
     * @param h
     * @param response
     */
//    @RequestMapping(value = "/get_cpacha",method = RequestMethod.GET)
//    public void getCpacha(HttpServletResponse response, HttpServletRequest request,
//                                  @RequestParam(value="vl",defaultValue="4",required=false) Integer vl,
//                                  @RequestParam(value="w",defaultValue="98",required=false) Integer w,
//                                  @RequestParam(value="h",defaultValue="33",required=false) Integer h
//                                  ){
//        System.out.println("获取验证码");
//        CpachaUtil cpachaUtil = new CpachaUtil(vl, w, h);
//        String generatorVCode = cpachaUtil.generatorVCode();
//        request.getSession().setAttribute("loginCpacha", generatorVCode);
//        BufferedImage generatorRotateVCodeImage = cpachaUtil.generatorRotateVCodeImage(generatorVCode, true);
//        try {
//            ImageIO.setUseCache(false);
//            ImageIO.write(generatorRotateVCodeImage, "gif", response.getOutputStream());
////            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
////            encoder.encode(generatorRotateVCodeImage);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//    }
    /**
     * 登录表单提交
     * 分为学生、教师、教务员
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "login",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Map<String,Object>> login(
            @RequestBody Map<String, String> map,
            HttpServletRequest request
    ){
        Map<String, Map<String,Object>> result = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> meta = new HashMap<>();
        Map<String, Object> user = new HashMap<>();
        Long username =  Long.parseLong(map.get("username"));
        String password = map.get("password");
        String type = map.get("type");
//        if(StringUtils.isEmpty(username)){
//            ret.put("type", "error");
//            ret.put("msg", "用户名不能为空!");
//            return ret;
//        }
//        if(StringUtils.isEmpty(password)){
//            ret.put("type", "error");
//            ret.put("msg", "密码不能为空!");
//            return ret;
//        }

//        if(StringUtils.isEmpty(verification)){
//            ret.put("type", "error");
//            ret.put("msg", "验证码不能为空!");
//            return ret;
//        }
//        String loginCpacha = (String)request.getSession().getAttribute("loginCpacha");
//        if(StringUtils.isEmpty(loginCpacha)){
//            ret.put("type", "error");
//            ret.put("msg", "长时间未操作，会话已失效，请刷新后重试!");
//            return ret;
//        }
//        if(!verification.toUpperCase().equals(loginCpacha.toUpperCase())){
//            ret.put("type", "error");
//            ret.put("msg", "验证码错误!");
//            return ret;
//        }
//        request.getSession().setAttribute("loginCpacha", null);
        //从数据库中去查找用户
//        if(type == 1){
//            //管理员
//            User user = userService.findByUserName(username);
//            if(user == null){
//                ret.put("type", "error");
//                ret.put("msg", "不存在该用户!");
//                return ret;
//            }
//            if(!password.equals(user.getPassword())){
//                ret.put("type", "error");
//                ret.put("msg", "密码错误!");
//                return ret;
//            }
//            request.getSession().setAttribute("user", user);
//        }
//        if(type == 2){
//            //学生
//            Student student = studentService.findByUserName(username);
//            if(student == null){
//                ret.put("type", "error");
//                ret.put("msg", "不存在该学生!");
//                return ret;
//            }
//            if(!password.equals(student.getPassword())){
//                ret.put("type", "error");
//                ret.put("msg", "密码错误!");
//                return ret;
//            }
//            request.getSession().setAttribute("student", student);
//        }
//        request.getSession().setAttribute("userType", type);
//        ret.put("type", "success");
//        ret.put("msg", "登录成功!");
        /*
        学生登录表单业务逻辑
         */
        if (type.equals("student")){
            Student student = studentService.findByStudentId(username);
            if(student == null){
                meta.put("status",400);
                result.put("meta",meta);
                return result;
            }
            if(!password.equals(student.getPassword())){
                meta.put("status",400);
                result.put("meta",meta);
                return result;
            }
            //登录成功执行一下操作
            user.put("type","student");
            user.put("id",student.getStuId());
            user.put("name",student.getStuName());
            user.put("gradePoint","");
            data.put("user",user);
            data.put("username",map.get("username"));
            meta.put("status",200);
        }
        /*
        教师登录表单业务逻辑
         */
        else if (type.equals("teacher")){
            Teacher teacher = teacherService.findByTeacherId(username);
            if(teacher == null){
                meta.put("status",400);
                result.put("meta",meta);
                return result;
            }
            if(!password.equals(teacher.getPassword())){
                meta.put("status",400);
                result.put("meta",meta);
                return result;
            }
            //登录成功执行一下操作
            user.put("type","teacher");
            user.put("id",teacher.getTeaId());
            user.put("name",teacher.getTeaName());

            data.put("user",user);
            data.put("username",map.get("username"));
            meta.put("status",200);
        }
        else {

        }
        result.put("data",data);
        result.put("meta",meta);
        return result ;
    }
}
